﻿using System;
using System.Linq;
using System.IO;

namespace Bettzueche.RLGlue.Codec.Network {
    /// <summary>
    /// Specialized BinaryWriter, who writes in Big Endian.<para>
    /// This is necessary, because the RLGlue.exe always reads in BigEndian</para>
    /// </summary>
    class RLGlueBinaryWriter : BinaryWriter {

        /// <summary>
        /// Initializes a new instance of the <see cref="RLGlueBinaryWriter"/> class.
        /// </summary>
        /// <param name="output">The output.</param>
        public RLGlueBinaryWriter(MemoryStream output) : base(output){

        }

        /// <summary>
        /// Writes a four-byte signed integer to the current stream and advances the stream position by four bytes.
        /// </summary>
        /// <param name="value">The four-byte signed integer to write.</param>
        /// <exception cref="T:System.IO.IOException">An I/O error occurs. </exception>
        /// <exception cref="T:System.ObjectDisposedException">The stream is closed. </exception>
        public override void Write(int value) {
            writeBigEndian(BitConverter.GetBytes(value));
        }

        /// <summary>
        /// Writes an eight-byte floating-point value to the current stream and advances the stream position by eight bytes.
        /// </summary>
        /// <param name="value">The eight-byte floating-point value to write.</param>
        /// <exception cref="T:System.IO.IOException">An I/O error occurs. </exception>
        /// <exception cref="T:System.ObjectDisposedException">The stream is closed. </exception>
        public override void Write(double value) {
            writeBigEndian(BitConverter.GetBytes(value));
        }

        // //used for char-sending
        //public override void Write(byte[] buffer) {
        //    WriteBigEndian(buffer);
        //}

        /// <summary>
        /// Writes the big endian.
        /// </summary>
        /// <param name="bytes">The bytes.</param>
        void writeBigEndian(byte[] bytes) {
            if (BitConverter.IsLittleEndian)
                Array.Reverse(bytes);
            base.Write(bytes);
        }

    }
}
